import { Component, ReactNode } from "react";
import { View, Textarea, Text } from "@tarojs/components";
import { AtList, AtListItem, AtImagePicker, AtButton, AtNavBar } from "taro-ui";
import Taro from "@tarojs/taro";
import Req, { BASE_URL } from "../../utils/request";
import { isEmpty, uploadImgConvertUrl } from "../../utils/kit";
import "./index.scss";
import { getToken } from "../../utils/auth";
export default class RegulatorForm extends Component {
  state = {
    memo: "",
    files: [],
    title: "",
    projectName: "",
    reactionId:"",
    fujian: [], //附件
  };
  onChange = (files) => {
    this.setState({
      files,
    });
  };
  componentDidMount(): void {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      Req.get("/project/supervision/" + router.params.id).then((r) => {
        if (r.code === 200) {
          this.setState({
            projectName: r.data.projectName,
            title: r.data.title,
          });
          if(r.data.reactionList && r.data.reactionList.length){
            const { id, memo, reactionFile, reactionImg }:any =r.data.reactionList[0];
            let _files = [];
            if (reactionImg) {
              _files = reactionImg.split(",").map((e) => {
                return {
                  url: BASE_URL + e,
                };
              });
            }
            if (reactionFile) {
              this.setState({
                fujian:reactionFile.split(",")
              })
            }
            
            this.setState({
              memo,
              reactionId:id,
              files:_files,
            })        
          }
        }
      });
    }
  }

  uploadFujian = async (files = []) => {
    let results: any[] = [];
    const token = getToken();
    for (const file of files) {
      if (typeof file === "string") {
        results.push({
          fileName: file,
        });
        continue;
      }
      const formData = new FormData();
      formData.append("file", file);
      const response = await fetch(`${BASE_URL}/common/upload`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: formData,
      });
      let r = await response.json();
      results.push(r);
    }
    return results;
  };

  onSub = (approvalState: number) => {
    const { files, fujian, memo,reactionId } = this.state;
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      uploadImgConvertUrl(files).then((results) => {
        let img = results
          .map((e: any) => {
            if (e?.data) {
              return JSON.parse(e.data)?.fileName;
            } else {
              return e.fileName;
            }
          })
          .join(",");
        this.uploadFujian(fujian).then((r) => {
          Req.post(
            "/project/supervision/reaction",
            {
              supervisionId: router.params.id,
              memo,
              reactionFile: r.map((e) => e.fileName).join(","),
              reactionImg: img,
              approvalState: approvalState,
              ...(
                !isEmpty(reactionId) && {
                  id:reactionId
                }
              )
            },
            {
              header: {
                "content-type": "application/x-www-form-urlencoded",
              },
            }
          )
            .then((r) => {
              if (r.code === 200) {
                Taro.eventCenter.trigger("refreshData", { force: true });
                Taro.navigateBack();
              }
            })
            .catch((e) => {});
        });
      });
    }
  };
  render(): ReactNode {
    const { memo, files, projectName, title, fujian } = this.state;
    return (
      <View className="rf-container list-form-page">
        <AtNavBar
          onClickLeftIcon={() => {
            Taro.navigateBack();
          }}
          leftIconType="chevron-left"
          leftText="返回"
          color="#3051BE"
        >
          <View>问题整改</View>
        </AtNavBar>
        <AtList className="list-form-content">
          <AtListItem
            title="项目名称"
            className="form-list-item no-active-effect-item"
            note={
              <View>
                <Text>{projectName}</Text>
              </View>
            }
          />
          <AtListItem
            title="监管标题"
            className="form-list-item no-active-effect-item"
            note={
              <View>
                <Text>{title}</Text>
              </View>
            }
          />
          <AtListItem
            title="反馈结果"
            className="form-list-item no-active-effect-item remark-form-item no-arrow-space"
            note={
              <View>
                <Textarea
                  value={memo}
                  onInput={(e) => {
                    this.setState({
                      memo: e.detail.value,
                    });
                  }}
                  className="remark-textarea"
                  placeholder="请输入文字"
                />
              </View>
            }
            extraText={
              <View className="img-picker">
                <AtImagePicker
                  length={1}
                  files={this.state.files}
                  onChange={this.onChange}
                />
              </View>
            }
          />
          <AtListItem
            title={"附件"}
            className="form-list-item no-active-effect-item"
            note={
              <View className="pj-box">
                <label for="fileInput">
                  <AtButton size="small">选择文件</AtButton>
                </label>
                <View>
                  {fujian.map((e: string | any, i) => (
                    <View key={i} className="fileName">
                      {typeof e === "string" ? e : e.name}
                    </View>
                  ))}
                </View>
                <input
                  id="fileInput"
                  type="file"
                  multiple
                  style={{
                    display: "none",
                  }}
                  onChange={(e: any) => {
                    const files = Array.from(e.target.files);
                    this.setState({
                      fujian: files,
                    });
                  }}
                />
              </View>
            }
          />
        </AtList>
        <View className="bottom-btn flex-box">
          <AtButton
            onClick={() => {
              this.onSub(3);
            }}
            circle
            className="primary-btn-color"
            type="primary"
          >
            暂存
          </AtButton>
          <AtButton
            onClick={() => {
              this.onSub(1);
            }}
            circle
            className="primary-btn-color"
            type="primary"
          >
            提交
          </AtButton>
        </View>
      </View>
    );
  }
}
